<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>JavaScript 异步编程 | Justic</title><meta name="keywords" content="JavaScript"><meta name="author" content="Justic"><meta name="copyright" content="Justic"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="一、Generator函数1、基本使用Generator函数也称之为生成器函数，可以用来生成迭代器，。也就是可以通过for…of来遍历Generator函数.并且Generator函数提供了一种异步编程的解决方案。 生成器函数和普通函数不一样，普通函数是一旦调用就会执行完毕，但是生成器函数中间可以暂停，也就是执行一会歇一会。 Generator函数的创建      function* go() &amp;">
<meta property="og:type" content="article">
<meta property="og:title" content="JavaScript 异步编程">
<meta property="og:url" content="http://example.com/2022/07/13/JavaScript/JavaScript%20%E9%9D%A2%E8%AF%95%E7%B2%BE%E8%AE%B2/JavaScript%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B/index.html">
<meta property="og:site_name" content="Justic">
<meta property="og:description" content="一、Generator函数1、基本使用Generator函数也称之为生成器函数，可以用来生成迭代器，。也就是可以通过for…of来遍历Generator函数.并且Generator函数提供了一种异步编程的解决方案。 生成器函数和普通函数不一样，普通函数是一旦调用就会执行完毕，但是生成器函数中间可以暂停，也就是执行一会歇一会。 Generator函数的创建      function* go() &amp;">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/j3/wallhaven-j3qq15.jpg">
<meta property="article:published_time" content="2022-07-13T12:05:37.000Z">
<meta property="article:modified_time" content="2022-07-14T13:03:01.339Z">
<meta property="article:author" content="Justic">
<meta property="article:tag" content="JavaScript">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/j3/wallhaven-j3qq15.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="http://example.com/2022/07/13/JavaScript/JavaScript%20%E9%9D%A2%E8%AF%95%E7%B2%BE%E8%AE%B2/JavaScript%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'JavaScript 异步编程',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-07-14 21:03:01'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><!-- hexo injector head_end start --><link rel="stylesheet" href="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/clock.min.css" /><!-- hexo injector head_end end --><meta name="generator" content="Hexo 6.2.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="https://portrait.gitee.com/uploads/avatars/user/2982/8948190_JIAXInT_1624177607.png!avatar200" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">22</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">2</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">3</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-graduation-cap"></i><span> 博文</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/project/"><i class="fa-fw fas fa-images"></i><span> 项目</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于笔者</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/j3/wallhaven-j3qq15.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Justic</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-graduation-cap"></i><span> 博文</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/project/"><i class="fa-fw fas fa-images"></i><span> 项目</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于笔者</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">JavaScript 异步编程</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-07-13T12:05:37.000Z" title="发表于 2022-07-13 20:05:37">2022-07-13</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-07-14T13:03:01.339Z" title="更新于 2022-07-14 21:03:01">2022-07-14</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/JavaScript/">JavaScript</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">6.8k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>31分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="JavaScript 异步编程"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span><span class="post-meta-separator">|</span><span class="post-meta-commentcount"><i class="far fa-comments fa-fw post-meta-icon"></i><span class="post-meta-label">评论数:</span><a href="/2022/07/13/JavaScript/JavaScript%20%E9%9D%A2%E8%AF%95%E7%B2%BE%E8%AE%B2/JavaScript%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B/#post-comment" itemprop="discussionUrl"><span class="valine-comment-count" data-xid="/2022/07/13/JavaScript/JavaScript%20%E9%9D%A2%E8%AF%95%E7%B2%BE%E8%AE%B2/JavaScript%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B/" itemprop="commentCount"><i class="fa-solid fa-spinner fa-spin"></i></span></a></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="一、Generator函数"><a href="#一、Generator函数" class="headerlink" title="一、Generator函数"></a>一、Generator函数</h1><h2 id="1、基本使用"><a href="#1、基本使用" class="headerlink" title="1、基本使用"></a>1、基本使用</h2><p>Generator函数也称之为生成器函数，可以用来生成迭代器，。也就是可以通过for…of来遍历Generator函数.并且Generator函数提供了一种异步编程的解决方案。</p>
<p>生成器函数和普通函数不一样，普通函数是一旦调用就会执行完毕，但是生成器函数中间可以暂停，也就是执行一会歇一会。</p>
<p>Generator函数的创建</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">     </span><br><span class="line"><span class="keyword">function</span>* <span class="title function_">go</span>(<span class="params"></span>) &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="number">1</span>);</span><br><span class="line">        <span class="keyword">let</span> a = <span class="keyword">yield</span> <span class="string">&#x27;a&#x27;</span>;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="number">2</span>);</span><br><span class="line">      </span><br><span class="line">        <span class="keyword">let</span> b = <span class="keyword">yield</span> a;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="number">3</span>);</span><br><span class="line">        <span class="keyword">return</span> b;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line"><span class="keyword">let</span> it = <span class="title function_">go</span>();</span><br><span class="line"><span class="keyword">let</span> r1 = it.<span class="title function_">next</span>();</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(r1);</span><br><span class="line"><span class="keyword">let</span> r2 = it.<span class="title function_">next</span>(<span class="string">&#x27;b的值&#x27;</span>);</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(r2);</span><br><span class="line"><span class="keyword">let</span> r4 = it.<span class="title function_">next</span>(<span class="string">&#x27;c的值&#x27;</span>);</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(r4);</span><br></pre></td></tr></table></figure>

<p>如果第一次执行next方法给变量a输入值应该怎样传值？</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">   </span><br><span class="line"><span class="keyword">function</span>* <span class="title function_">go</span>(<span class="params">str</span>) &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="number">1</span>);</span><br><span class="line">        <span class="keyword">let</span> a = <span class="keyword">yield</span> str;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="number">2</span>);</span><br><span class="line">        <span class="comment">// 这行代码实现了输入与输出，本次的输出放在了yield的后面，下次的输入放在了yield的前面。</span></span><br><span class="line">        <span class="keyword">let</span> b = <span class="keyword">yield</span> a;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="number">3</span>);</span><br><span class="line">        <span class="keyword">return</span> b;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 在这里先去调用一下生成器函数，但是注意，调用它不会立即执行</span></span><br><span class="line">    <span class="comment">// 该函数在这里会返回一个迭代器</span></span><br><span class="line"><span class="keyword">let</span> it = <span class="title function_">go</span>(<span class="string">&#x27;a的值&#x27;</span>); <span class="comment">// 调用的时候进行值的传递</span></span><br><span class="line"><span class="comment">//  下面需要调用next()函数</span></span><br><span class="line"><span class="keyword">let</span> r1 = it.<span class="title function_">next</span>();</span><br><span class="line">     </span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(r1);</span><br><span class="line"><span class="keyword">let</span> r2 = it.<span class="title function_">next</span>(<span class="string">&#x27;b的值&#x27;</span>);</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(r2);</span><br><span class="line">    </span><br><span class="line"><span class="keyword">let</span> r4 = it.<span class="title function_">next</span>(<span class="string">&#x27;c的值&#x27;</span>);</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(r4);</span><br><span class="line">       </span><br></pre></td></tr></table></figure>

<h2 id="2、next方法参数"><a href="#2、next方法参数" class="headerlink" title="2、next方法参数"></a>2、next方法参数</h2><p>在上一个案例中,给next方法添加了相应的参数，那么该参数会 被当作上一条yield语句的返回值。</p>
<p>下面看一下如下程序，判断其对应的输出结果。(直接看程序)</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">function</span>* <span class="title function_">test</span>(<span class="params">num</span>) &#123;</span><br><span class="line">     <span class="keyword">let</span> x = <span class="number">3</span> * (<span class="title function_">yield</span>(num + <span class="number">1</span>));</span><br><span class="line">     <span class="keyword">let</span> y = <span class="title function_">yield</span>(x / <span class="number">3</span>);</span><br><span class="line">     <span class="keyword">return</span> (x + y + num);</span><br><span class="line"> &#125;</span><br><span class="line"> <span class="keyword">let</span> n = <span class="title function_">test</span>(<span class="number">6</span>);</span><br><span class="line"> <span class="variable language_">console</span>.<span class="title function_">log</span>(n.<span class="title function_">next</span>());</span><br><span class="line"> <span class="variable language_">console</span>.<span class="title function_">log</span>(n.<span class="title function_">next</span>());</span><br><span class="line"> <span class="variable language_">console</span>.<span class="title function_">log</span>(n.<span class="title function_">next</span>());</span><br></pre></td></tr></table></figure>

<p>输出结果如下：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">&#123;value: 7, done: false&#125;</span><br><span class="line">&#123;value: NaN, done: false&#125;</span><br><span class="line">&#123;value: NaN, done: true&#125;</span><br></pre></td></tr></table></figure>

<p>现在将程序修改成如下的形式：</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">function</span>* <span class="title function_">test</span>(<span class="params">num</span>) &#123;</span><br><span class="line">    <span class="keyword">let</span> x = <span class="number">3</span> * (<span class="title function_">yield</span>(num + <span class="number">1</span>));</span><br><span class="line">    <span class="keyword">let</span> y = <span class="title function_">yield</span>(x / <span class="number">3</span>);</span><br><span class="line">    <span class="keyword">return</span> (x + y + num);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> n = <span class="title function_">test</span>(<span class="number">6</span>);</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(n.<span class="title function_">next</span>());</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(n.<span class="title function_">next</span>(<span class="number">3</span>));</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(n.<span class="title function_">next</span>(<span class="number">3</span>));</span><br></pre></td></tr></table></figure>

<p>输出结果如下：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">&#123;value: 7, done: false&#125;</span><br><span class="line">&#123;value: 3, done: false&#125;</span><br><span class="line">&#123;value: 18, done: true&#125;</span><br></pre></td></tr></table></figure>

<p>注意：由于next方法的参数表示上一条yield语句的返回值，所以第一次使用next方法时不能带参数。</p>
<p>也就是第一次使用next方法时是用来启动遍历器对象的。</p>
<h2 id="3、for…of循环"><a href="#3、for…of循环" class="headerlink" title="3、for…of循环"></a>3、for…of循环</h2><p>for…of循环可以自动遍历Generator函数，且此时不再需要调用next方法。</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">function</span>* <span class="title function_">test</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">yield</span> <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">yield</span> <span class="number">2</span>;</span><br><span class="line">    <span class="keyword">yield</span> <span class="number">3</span>;</span><br><span class="line">    <span class="keyword">yield</span> <span class="number">4</span>;</span><br><span class="line">    <span class="keyword">yield</span> <span class="number">5</span>;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">6</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> v <span class="keyword">of</span> <span class="title function_">test</span>()) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(v);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>注意：一旦next()方法返回的对象的done属性为true, for…of循环就会终止，且不包含该返回对象，所以上面的return语句不在for…of循环中。</p>
<p>在前面的课程中讲过，由于JavaScript对象没有遍历的接口，无法使用for…of进行遍历，那么现在可以通过Generator函数为它加上这个接口就可以了。</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> user = &#123;</span><br><span class="line">    <span class="attr">name</span>: <span class="string">&#x27;zs&#x27;</span>,</span><br><span class="line">    <span class="attr">age</span>: <span class="number">18</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span>* <span class="title function_">test</span>(<span class="params">obj</span>) &#123;</span><br><span class="line">    <span class="keyword">let</span> keys = <span class="title class_">Reflect</span>.<span class="title function_">ownKeys</span>(obj);</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> key <span class="keyword">of</span> keys) &#123;</span><br><span class="line">        <span class="keyword">yield</span> [key, obj[key]];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> item <span class="keyword">of</span> <span class="title function_">test</span>(user)) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(item);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="4、yield-语句"><a href="#4、yield-语句" class="headerlink" title="4、yield* 语句"></a>4、yield* 语句</h2><p>如果在Generator函数内部调用一个Generator函数，默认情况下是没有效果的。</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">function</span>* <span class="title function_">test</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">yield</span> <span class="string">&#x27;a&#x27;</span>;</span><br><span class="line">    <span class="keyword">yield</span> <span class="string">&#x27;b&#x27;</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span>* <span class="title function_">test1</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">yield</span> <span class="string">&#x27;x&#x27;</span>;</span><br><span class="line">    <span class="title function_">test</span>();</span><br><span class="line">    <span class="keyword">yield</span> <span class="string">&#x27;y&#x27;</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> v <span class="keyword">of</span> <span class="title function_">test1</span>()) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(v);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>要解决这个问题，需要用到 yield* 语句，用来在一个Generator函数中执行另外一个Generator函数。</p>
<p>上面的程序，修改成如下的形式：</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">function</span>* <span class="title function_">test</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">yield</span> <span class="string">&#x27;a&#x27;</span>;</span><br><span class="line">    <span class="keyword">yield</span> <span class="string">&#x27;b&#x27;</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span>* <span class="title function_">test1</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">yield</span> <span class="string">&#x27;x&#x27;</span>;</span><br><span class="line">    <span class="keyword">yield</span>* <span class="title function_">test</span>();</span><br><span class="line">    <span class="keyword">yield</span> <span class="string">&#x27;y&#x27;</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> v <span class="keyword">of</span> <span class="title function_">test1</span>()) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(v);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其实上面的代码与下面的代码是等价的关系</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">function</span>* <span class="title function_">test</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">yield</span> <span class="string">&#x27;a&#x27;</span>;</span><br><span class="line">    <span class="keyword">yield</span> <span class="string">&#x27;b&#x27;</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span>* <span class="title function_">test1</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">yield</span> <span class="string">&#x27;x&#x27;</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> v <span class="keyword">of</span> <span class="title function_">test</span>()) &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(v);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">yield</span> <span class="string">&#x27;y&#x27;</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> v <span class="keyword">of</span> <span class="title function_">test1</span>()) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(v);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>所以 yield* 语句等同于在Generator函数内部部署了一个for…of循环。</p>
<p>看一下，下面的伪代码</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">function</span>* <span class="title function_">test</span>(<span class="params"></span>) &#123;</span><br><span class="line">     <span class="keyword">yield</span>* it1;</span><br><span class="line">     <span class="keyword">yield</span>* it2;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>

<p>上面的代码等同于下面的代码</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">function</span>* <span class="title function_">test</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> value <span class="keyword">of</span> it1) &#123;</span><br><span class="line">        <span class="keyword">yield</span> value;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> value <span class="keyword">of</span> it2) &#123;</span><br><span class="line">        <span class="keyword">yield</span> value;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果 yield* 后面跟着一个数组，会出现什么情况呢？</p>
<p>由于数组原生支持遍历器，因此会遍历数组成员。</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">function</span>* <span class="title function_">test</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">yield</span>*[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>]</span><br><span class="line">&#125;</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="title function_">test</span>().<span class="title function_">next</span>())</span><br></pre></td></tr></table></figure>

<p>上面的代码输出的结果为：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">&#123;value: 1, done: false&#125;</span><br></pre></td></tr></table></figure>

<p>通过上面的输出结果可以看出，加了星号后表示返回的是数组的遍历器对象。</p>
<p>如果不加星号，输出结果如下：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">&#123;value: Array(6), done: false&#125;</span><br></pre></td></tr></table></figure>

<p>不加星号返回的是整个数组。</p>
<p>所以，任何数据结构只要有了Iterator接口，就可以使用yield*来进行遍历。</p>
<p>下面再一段程序，看一下对应的输出结果</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">function</span>* <span class="title function_">test</span>(<span class="params"></span>) &#123;</span><br><span class="line">         <span class="keyword">yield</span> <span class="number">1</span>;</span><br><span class="line">         <span class="keyword">yield</span> <span class="number">2</span>;</span><br><span class="line">         <span class="keyword">return</span> <span class="string">&#x27;test&#x27;</span>;</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">     <span class="keyword">function</span>* <span class="title function_">test1</span>(<span class="params"></span>) &#123;</span><br><span class="line">         <span class="keyword">yield</span> <span class="number">3</span>;</span><br><span class="line">         <span class="keyword">let</span> value = <span class="keyword">yield</span>* <span class="title function_">test</span>();</span><br><span class="line">         <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;value=&#x27;</span>, value);</span><br><span class="line">         <span class="keyword">yield</span> <span class="number">4</span>;</span><br><span class="line">     &#125;</span><br><span class="line">     <span class="keyword">let</span> it = <span class="title function_">test1</span>();</span><br><span class="line">     <span class="variable language_">console</span>.<span class="title function_">log</span>(it.<span class="title function_">next</span>());</span><br><span class="line">     <span class="variable language_">console</span>.<span class="title function_">log</span>(it.<span class="title function_">next</span>());</span><br><span class="line">     <span class="variable language_">console</span>.<span class="title function_">log</span>(it.<span class="title function_">next</span>());</span><br><span class="line">     <span class="variable language_">console</span>.<span class="title function_">log</span>(it.<span class="title function_">next</span>());</span><br><span class="line">     <span class="variable language_">console</span>.<span class="title function_">log</span>(it.<span class="title function_">next</span>());</span><br></pre></td></tr></table></figure>

<p>输出的结果如下：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">&#123;value: 3, done: false&#125;</span><br><span class="line">&#123;value: 1, done: false&#125;</span><br><span class="line">&#123;value: 2, done: false&#125;</span><br><span class="line">value= test   &#123;value: 4, done: false&#125;</span><br><span class="line">&#123;value: undefined, done: true&#125;</span><br></pre></td></tr></table></figure>

<p>通过上面的代码可以，发现test函数中的return值，给了test1函数中的value这个变量。</p>
<h2 id="5、关于Generator函数中的this问题"><a href="#5、关于Generator函数中的this问题" class="headerlink" title="5、关于Generator函数中的this问题"></a>5、关于Generator函数中的this问题</h2><p>在讲解具体的this问题之前，先看一下下面的代码，是否有错误？</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">function</span>* <span class="title class_">Person</span>() &#123;</span><br><span class="line">    <span class="keyword">yield</span> <span class="variable language_">this</span>.<span class="property">name</span> = <span class="string">&#x27;zs&#x27;</span>;</span><br><span class="line">    <span class="keyword">yield</span> <span class="variable language_">this</span>.<span class="property">age</span> = <span class="number">18</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> person = <span class="keyword">new</span> <span class="title class_">Person</span>();</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(person.<span class="property">name</span>);</span><br></pre></td></tr></table></figure>

<p>执行上面的代码后，发现是有错误的，因为Person既是构造函数，又是一个Generator函数，所以使用new命令就无法创建Person的对象。</p>
<p>怎样解决这个问题呢？</p>
<p>首先创建一个空对象，然后使用bind方法绑定Generator函数内部的this。这样，这个空对象就是Generator函数的实例对象了。</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">function</span>* <span class="title class_">Person</span>() &#123;</span><br><span class="line">     <span class="keyword">yield</span> <span class="variable language_">this</span>.<span class="property">name</span> = <span class="string">&#x27;zs&#x27;</span>;</span><br><span class="line">     <span class="keyword">yield</span> <span class="variable language_">this</span>.<span class="property">age</span> = <span class="number">18</span>;</span><br><span class="line"> &#125;</span><br><span class="line"> <span class="keyword">let</span> person = &#123;&#125;</span><br><span class="line"> <span class="keyword">let</span> obj = <span class="title class_">Person</span>.<span class="title function_">bind</span>(person)();</span><br><span class="line"> <span class="variable language_">console</span>.<span class="title function_">log</span>(obj.<span class="title function_">next</span>());</span><br></pre></td></tr></table></figure>

<h2 id="6、Generator函数应用场景"><a href="#6、Generator函数应用场景" class="headerlink" title="6、Generator函数应用场景"></a>6、Generator函数应用场景</h2><h3 id="6-1-状态处理"><a href="#6-1-状态处理" class="headerlink" title="6.1 状态处理"></a>6.1 状态处理</h3><p>单击按钮实现图片切换，这个案例如果按照以前的做法，如下：</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> button = <span class="variable language_">document</span>.<span class="title function_">getElementById</span>(<span class="string">&#x27;btn&#x27;</span>) <span class="comment">//找到按钮</span></span><br><span class="line">      <span class="keyword">let</span> mm = <span class="variable language_">document</span>.<span class="title function_">getElementById</span>(<span class="string">&#x27;mv&#x27;</span>) <span class="comment">//找到img标签</span></span><br><span class="line">      <span class="keyword">let</span> flag = <span class="number">0</span></span><br><span class="line">      button.<span class="property">onclick</span> = <span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">          <span class="comment">//将img标签的src属性的值，换成另外一张图片的地址.</span></span><br><span class="line">          <span class="keyword">if</span> (flag === <span class="number">0</span>) &#123;</span><br><span class="line">              mm.<span class="property">src</span> = <span class="string">&#x27;images/b.jpg&#x27;</span>;</span><br><span class="line">              flag = <span class="number">1</span>;</span><br><span class="line">          &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">              mm.<span class="property">src</span> = <span class="string">&#x27;images/a.jpg&#x27;</span>;</span><br><span class="line">              flag = <span class="number">0</span>;</span><br><span class="line">          &#125;</span><br><span class="line"></span><br><span class="line">      &#125;</span><br></pre></td></tr></table></figure>

<p>使用 Generator函数处理</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> button = <span class="variable language_">document</span>.<span class="title function_">getElementById</span>(<span class="string">&#x27;btn&#x27;</span>) <span class="comment">//找到按钮</span></span><br><span class="line"><span class="keyword">let</span> mm = <span class="variable language_">document</span>.<span class="title function_">getElementById</span>(<span class="string">&#x27;mv&#x27;</span>) <span class="comment">//找到img标签</span></span><br><span class="line"><span class="keyword">let</span> it = <span class="title function_">f</span>(<span class="number">0</span>);</span><br><span class="line">button.<span class="property">onclick</span> = <span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">    it.<span class="title function_">next</span>();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span>* <span class="title function_">f</span>(<span class="params">flag</span>) &#123;</span><br><span class="line">    <span class="keyword">while</span> (<span class="literal">true</span>) &#123;</span><br><span class="line">        mm.<span class="property">src</span> = <span class="string">&#x27;images/b.jpg&#x27;</span>;</span><br><span class="line">        <span class="keyword">yield</span> flag;</span><br><span class="line">        mm.<span class="property">src</span> = <span class="string">&#x27;images/a.jpg&#x27;</span>;</span><br><span class="line">        <span class="keyword">yield</span> flag;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>使用Generator函数处理更加简单，并且更加符合函数的编程思想。（注意步骤的分析)</p>
<h3 id="6-2-异步处理"><a href="#6-2-异步处理" class="headerlink" title="6.2 异步处理"></a>6.2 异步处理</h3><p>前面讲过，Generator函数提供了一种异步处理的解决方案，而AJAX是典型的异步操作。</p>
<p>下面伪代码，直接看一下</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">function</span>* <span class="title function_">main</span>(<span class="params"></span>) &#123;</span><br><span class="line">  <span class="keyword">let</span> result = <span class="keyword">yield</span> <span class="title function_">request</span>(<span class="string">&quot;http://xxx.com/api&quot;</span>);</span><br><span class="line">  <span class="keyword">let</span> resp = <span class="title class_">JSON</span>.<span class="title function_">parse</span>(result);</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(resp.<span class="property">value</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">request</span>(<span class="params">url</span>) &#123;</span><br><span class="line">  <span class="title function_">makeAjaxCall</span>(url, <span class="keyword">function</span>(<span class="params">response</span>)&#123;</span><br><span class="line">    it.<span class="title function_">next</span>(response);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> it = <span class="title function_">main</span>();</span><br><span class="line">it.<span class="title function_">next</span>();</span><br></pre></td></tr></table></figure>

<p>注意：在makeAjaxCall函数中的next( )方法，一定要把response作为它的参数。</p>
<p>因为该参数会给main函数中的result变量，最终对result进行处理。</p>
<p>并且，上面的写法几乎与同步操作的写法完全一样，写起来非常简单。</p>
<h1 id="二、Promise对象"><a href="#二、Promise对象" class="headerlink" title="二、Promise对象"></a>二、Promise对象</h1><h2 id="1、Promise定义"><a href="#1、Promise定义" class="headerlink" title="1、Promise定义"></a>1、Promise定义</h2><h3 id="1-1-回调地狱问题"><a href="#1-1-回调地狱问题" class="headerlink" title="1.1 回调地狱问题"></a>1.1 回调地狱问题</h3><p>在讲解具体的Promise对象的定义前，先来讲解一下回调地狱的问题。</p>
<p>在开发中经常使用Ajax发送请求，那么就会出现如下的情况：</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">$.<span class="title function_">ajax</span>(url, <span class="title function_">success</span>(<span class="params"></span>) &#123;</span><br><span class="line">    $.<span class="title function_">ajax</span>(url2, <span class="title function_">success</span>(<span class="params"></span>) &#123;</span><br><span class="line">        $.<span class="title function_">ajax</span>(url3, <span class="title function_">success</span>(<span class="params"></span>) &#123;</span><br><span class="line"></span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>以上的代码反映了，在一个Ajax的回调中，又去发送了另外一个Ajax请求，依次类推，导致了多个回调函数的嵌套，导致代码不够直观并且难以维护，这就是常说的回调地狱。</p>
<p>所以在实际的开发中，不希望这种不断嵌套的回调，而是希望将这种多层变成一层。</p>
<p>要解决这个回调地狱的问题，就要用到Promise对象。</p>
<h3 id="同步模式"><a href="#同步模式" class="headerlink" title="同步模式"></a>同步模式</h3><p>同步模式指的就是代码中的任务依次执行。后一个任务必须等待前一个任务结束后，才能执行。程序的执行顺序与我们代码的编写顺序是完全一致的。</p>
<h3 id="异步模式"><a href="#异步模式" class="headerlink" title="异步模式"></a>异步模式</h3><p>异步模式对应的<code>API</code>是不会等待这个任务的结束才开始下一个任务，对于耗时操作，开启过后就立即往后执行下一个任务。</p>
<p>耗时任务的后续逻辑一般会通过回调函数的方式定义（例如ajax回调函数）。</p>
<h3 id="Promise概念与基本使用"><a href="#Promise概念与基本使用" class="headerlink" title="Promise概念与基本使用"></a>Promise概念与基本使用</h3><p>所谓的Promise就是一个对象，而Promise对象代表的是一个异步任务，也就是需要很长时间去执行的任务。</p>
<p>也就是通过Promise对象，可以将异步操作以同步操作的流程表达出来，避免了层层嵌套的回调函数问题，也就是回调地狱的问题。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> promise = <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="keyword">function</span>(<span class="params">resolve, reject</span>) &#123;</span><br><span class="line">            <span class="built_in">setTimeout</span>(<span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">                <span class="keyword">let</span> num = <span class="title class_">Math</span>.<span class="title function_">random</span>();</span><br><span class="line">                <span class="keyword">if</span> (num &gt; <span class="number">0.3</span>) &#123;</span><br><span class="line">                    <span class="title function_">resolve</span>(<span class="string">&#x27;成功了!&#x27;</span>)</span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                    <span class="title function_">reject</span>(<span class="string">&#x27;失败了&#x27;</span>)</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;, <span class="number">3000</span>)</span><br><span class="line">        &#125;)</span><br><span class="line">        promise.<span class="title function_">then</span>(<span class="keyword">function</span>(<span class="params">value</span>) &#123;</span><br><span class="line">            <span class="variable language_">console</span>.<span class="title function_">log</span>(value);</span><br><span class="line">        &#125;, <span class="keyword">function</span>(<span class="params">reason</span>) &#123;</span><br><span class="line">            <span class="variable language_">console</span>.<span class="title function_">log</span>(reason);</span><br><span class="line">        &#125;)</span><br></pre></td></tr></table></figure>

<h2 id="2-使用Promise封装AJAX操作"><a href="#2-使用Promise封装AJAX操作" class="headerlink" title="2 使用Promise封装AJAX操作"></a>2 使用Promise封装AJAX操作</h2><figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> getJSON = <span class="keyword">function</span>(<span class="params">url</span>) &#123;</span><br><span class="line">          <span class="keyword">let</span> p = <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="keyword">function</span>(<span class="params">resolve, reject</span>) &#123;</span><br><span class="line">              <span class="keyword">let</span> xhr = <span class="keyword">new</span> <span class="title class_">XMLHttpRequest</span>();</span><br><span class="line">              xhr.<span class="title function_">open</span>(<span class="string">&#x27;GET&#x27;</span>, url);</span><br><span class="line">              xhr.<span class="property">onreadystatechange</span> = handler;</span><br><span class="line">              xhr.<span class="property">responseType</span> = <span class="string">&#x27;json&#x27;</span>;</span><br><span class="line">              xhr.<span class="title function_">setRequestHeader</span>(<span class="string">&#x27;Accept&#x27;</span>, <span class="string">&#x27;application/json&#x27;</span>);</span><br><span class="line">              xhr.<span class="title function_">send</span>();</span><br><span class="line">              <span class="keyword">function</span> <span class="title function_">handler</span>(<span class="params"></span>) &#123;</span><br><span class="line">                  <span class="keyword">if</span> (xhr.<span class="property">readyState</span> === <span class="number">4</span>) &#123;</span><br><span class="line">                      <span class="keyword">if</span> (<span class="variable language_">this</span>.<span class="property">status</span> === <span class="number">200</span>) &#123;</span><br><span class="line">                          <span class="title function_">resolve</span>(<span class="variable language_">this</span>.<span class="property">response</span>)</span><br><span class="line">                      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                          <span class="title function_">reject</span>(<span class="keyword">new</span> <span class="title class_">Error</span>(<span class="variable language_">this</span>.<span class="property">statusText</span>));</span><br><span class="line">                      &#125;</span><br><span class="line">                  &#125;</span><br><span class="line">              &#125;</span><br><span class="line">          &#125;);</span><br><span class="line">          <span class="comment">//返回Promise对象</span></span><br><span class="line">          <span class="keyword">return</span> p;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="title function_">getJSON</span>(<span class="string">&#x27;http://localhost:3005/products&#x27;</span>).<span class="title function_">then</span>(<span class="keyword">function</span>(<span class="params">result</span>) &#123;</span><br><span class="line">          <span class="variable language_">console</span>.<span class="title function_">log</span>(result);</span><br><span class="line">      &#125;, <span class="keyword">function</span>(<span class="params">error</span>) &#123;</span><br><span class="line">          <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;出错了:&#x27;</span> + error)</span><br><span class="line">      &#125;)</span><br></pre></td></tr></table></figure>

<h2 id="3、Promise链式调用"><a href="#3、Promise链式调用" class="headerlink" title="3、Promise链式调用"></a>3、Promise链式调用</h2><p>与传统回调函数处理异步任务相比，<code>Promise</code>最大的优势就是可以实现链式调用。</p>
<p>这样可以最大程度的避免回调地狱的问题。</p>
<p><code>then</code>方法第一个参数是成功的回调，第二个参数是失败的回调，当然第二个参数是可以省略的。</p>
<p><code>then</code>方法最大的特点就是可以返回一个<code>Promise</code>对象。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> promise=<span class="title function_">ajax</span>(<span class="string">&#x27;/api/users.json&#x27;</span>)</span><br><span class="line"><span class="keyword">var</span> promise2=promise.<span class="title function_">then</span>(<span class="keyword">function</span> <span class="title function_">onFulfilled</span>(<span class="params">value</span>)&#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;onFulfilled&#x27;</span>,value)</span><br><span class="line">&#125;,<span class="keyword">function</span> <span class="title function_">onRejected</span>(<span class="params">error</span>)&#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;onRejected&#x27;</span>,error)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(promise2)<span class="comment">//输出的是一个promise对象</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(promise2===promise)<span class="comment">//返回值为false,所以这里的链式调用与前面我们学习的不一样，以前是通过返回this的方式来实现。而这里的then方法</span></span><br><span class="line"><span class="comment">//返回的是一个全新的	Promise对象。</span></span><br></pre></td></tr></table></figure>

<p>返回全新的<code>Promise</code>的目的，就是为了实现一个<code>Promise</code>的链条，也就是一个承诺结束后，返回一个新的承诺。每个承诺都可以负责一个异步任务，</p>
<p>相互之间没有什么影响，那么如果我们不断的链式调用<code>then</code>方法，然后这里每个<code>then</code>方法，都是为上一个<code>then</code>方法返回的<code>Promise</code> 对象添加状态明确后的回调。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">&lt;!<span class="variable constant_">DOCTYPE</span> html&gt;</span><br><span class="line"><span class="language-xml"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;<span class="name">head</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">&quot;X-UA-Compatible&quot;</span> <span class="attr">content</span>=<span class="string">&quot;IE=edge&quot;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">&quot;viewport&quot;</span> <span class="attr">content</span>=<span class="string">&quot;width=device-width, initial-scale=1.0&quot;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Promise链式调用<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;/<span class="name">head</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;<span class="name">body</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="keyword">let</span> getJson = <span class="keyword">function</span> (<span class="params">url</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="keyword">let</span> p = <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="keyword">function</span> (<span class="params">resolve, reject</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="keyword">let</span> xhr = <span class="keyword">new</span> <span class="title class_">XMLHttpRequest</span>();</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          xhr.<span class="title function_">open</span>(<span class="string">&quot;GET&quot;</span>, url);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          xhr.<span class="property">onreadystatechange</span> = handler;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          xhr.<span class="property">responseType</span> = <span class="string">&quot;json&quot;</span>;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          xhr.<span class="title function_">setRequestHeader</span>(<span class="string">&quot;Accept&quot;</span>, <span class="string">&quot;application/json&quot;</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          xhr.<span class="title function_">send</span>();</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="keyword">function</span> <span class="title function_">handler</span>(<span class="params"></span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            <span class="keyword">if</span> (xhr.<span class="property">readyState</span> === <span class="number">4</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">              <span class="keyword">if</span> (xhr.<span class="property">status</span> == <span class="number">200</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                <span class="title function_">resolve</span>(<span class="variable language_">this</span>.<span class="property">response</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">              &#125; <span class="keyword">else</span> &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                <span class="title function_">reject</span>(<span class="keyword">new</span> <span class="title class_">Error</span>(<span class="variable language_">this</span>.<span class="property">statusText</span>));</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">              &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="keyword">return</span> p;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      &#125;;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="keyword">var</span> promise = <span class="title function_">getJson</span>(<span class="string">&quot;http://localhost:3005/products&quot;</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="keyword">var</span> promise2 = promise.<span class="title function_">then</span>(</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="keyword">function</span> (<span class="params">result</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="variable language_">console</span>.<span class="title function_">log</span>(result);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="keyword">function</span> (<span class="params">err</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;出错了:&quot;</span> + err);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      );</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;promise2=&quot;</span>, promise2);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="variable language_">console</span>.<span class="title function_">log</span>(promise === promise2);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">    </span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;/<span class="name">body</span>&gt;</span></span></span><br><span class="line"><span class="language-xml"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">&lt;!<span class="variable constant_">DOCTYPE</span> html&gt;</span><br><span class="line"><span class="language-xml"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;<span class="name">head</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">&quot;X-UA-Compatible&quot;</span> <span class="attr">content</span>=<span class="string">&quot;IE=edge&quot;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">&quot;viewport&quot;</span> <span class="attr">content</span>=<span class="string">&quot;width=device-width, initial-scale=1.0&quot;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Promise链式调用<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;/<span class="name">head</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;<span class="name">body</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="keyword">let</span> getJson = <span class="keyword">function</span> (<span class="params">url</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="keyword">let</span> p = <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="keyword">function</span> (<span class="params">resolve, reject</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="keyword">let</span> xhr = <span class="keyword">new</span> <span class="title class_">XMLHttpRequest</span>();</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          xhr.<span class="title function_">open</span>(<span class="string">&quot;GET&quot;</span>, url);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          xhr.<span class="property">onreadystatechange</span> = handler;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          xhr.<span class="property">responseType</span> = <span class="string">&quot;json&quot;</span>;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          xhr.<span class="title function_">setRequestHeader</span>(<span class="string">&quot;Accept&quot;</span>, <span class="string">&quot;application/json&quot;</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          xhr.<span class="title function_">send</span>();</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="keyword">function</span> <span class="title function_">handler</span>(<span class="params"></span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            <span class="keyword">if</span> (xhr.<span class="property">readyState</span> === <span class="number">4</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">              <span class="keyword">if</span> (xhr.<span class="property">status</span> == <span class="number">200</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                <span class="title function_">resolve</span>(<span class="variable language_">this</span>.<span class="property">response</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">              &#125; <span class="keyword">else</span> &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                <span class="title function_">reject</span>(<span class="keyword">new</span> <span class="title class_">Error</span>(<span class="variable language_">this</span>.<span class="property">statusText</span>));</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">              &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="keyword">return</span> p;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      &#125;;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="title function_">getJson</span>(<span class="string">&quot;http://localhost:3005/products&quot;</span>)</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        .<span class="title function_">then</span>(<span class="keyword">function</span> (<span class="params">value</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="variable language_">console</span>.<span class="title function_">log</span>(value);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;111&quot;</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="keyword">return</span> <span class="title function_">getJson</span>(<span class="string">&quot;http://localhost:3005/cart&quot;</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;)</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        .<span class="title function_">then</span>(<span class="keyword">function</span> (<span class="params">value</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;then2=&quot;</span>, value);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;222&quot;</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;)</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        .<span class="title function_">then</span>(<span class="keyword">function</span> (<span class="params">value</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="variable language_">console</span>.<span class="title function_">log</span>(value);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;333&quot;</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;)</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        .<span class="title function_">then</span>(<span class="keyword">function</span> (<span class="params">value</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;444&quot;</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="keyword">return</span> <span class="string">&quot;abc&quot;</span>;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;)</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        .<span class="title function_">then</span>(<span class="keyword">function</span> (<span class="params">value</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;555555&quot;</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;then5=&quot;</span>, value);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">    </span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;/<span class="name">body</span>&gt;</span></span></span><br><span class="line"><span class="language-xml"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="4、Promise异常处理"><a href="#4、Promise异常处理" class="headerlink" title="4、Promise异常处理"></a>4、<code>Promise</code>异常处理</h2><p>如果<code>Promise</code>执行结果失败，会调用我们所为其添加的<code>onRejected</code>回调函数。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> promise=<span class="title function_">ajax</span>(<span class="string">&#x27;/api/users.json&#x27;</span>)</span><br><span class="line"><span class="keyword">var</span> promise2=promise.<span class="title function_">then</span>(<span class="keyword">function</span> <span class="title function_">onFulfilled</span>(<span class="params">value</span>)&#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;onFulfilled&#x27;</span>,value)</span><br><span class="line">&#125;,<span class="keyword">function</span> <span class="title function_">onRejected</span>(<span class="params">error</span>)&#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;onRejected&#x27;</span>,error)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>例如，我们请求了不存在地址，或者是我们在<code>ajax</code>方法内部出现了异常（<code>throw new Error()</code>），都会执行<code>onRejected</code>函数。</p>
<p>所以说<code>onRejected</code>就是处理<code>Promise</code>中的异常。当然关于异常处理，我们还有另外一种用户就是使用<code>Promise</code>对象的<code>catch</code>方法来完成。</p>
<p>下面，我们来实现以下</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="title function_">ajax</span>(<span class="string">&#x27;/api/users.json&#x27;</span>).<span class="title function_">then</span>(<span class="keyword">function</span> <span class="title function_">onFulfilled</span>(<span class="params">value</span>)&#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;onFulfilled&#x27;</span>,value)</span><br><span class="line">&#125;).<span class="title function_">catch</span>(<span class="keyword">function</span> <span class="title function_">onRejected</span>(<span class="params">error</span>)&#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;onRejected&#x27;</span>,error)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>在上面的代码中，使用<code>then</code>注册了成功的回调，使用<code>catch</code>来处理异常。</p>
<p>其实这个<code>catch</code>方法就是<code>then</code>方法的别名。</p>
<h2 id="5、Promise并行执行"><a href="#5、Promise并行执行" class="headerlink" title="5、Promise并行执行"></a>5、Promise并行执行</h2><p>例如，一个页面中有可能会与遇到多个请求服务端接口的情况，而这些请求之间没有相互的依赖关系。</p>
<p>那最好的选择就是同时请求服务端，避免一个一个的请求，而消耗过多的时间。</p>
<p>当然，你可能会说，这个实现起来非常的简单啊，把我们前面所写的<code>ajax</code>函数，多调用几次就可以了，如下所示：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="title function_">ajax</span>(<span class="string">&#x27;/api/users.json&#x27;</span>)</span><br><span class="line"><span class="title function_">ajax</span>(<span class="string">&#x27;/api/posts.json&#x27;</span>)</span><br></pre></td></tr></table></figure>

<p>但是问题是，我们怎么知道所有的请求都结束了呢？</p>
<p>当然，你可能会说，我们定义一个计数器，每个请求结束后，让这个计数器累加一下，当累加的个数，与我们的任务数相同后，就表示所有的任务结束了。</p>
<p>这种方式比较麻烦。为了解决这个问题，<code>Promise</code>中提供了一个<code>all</code>方法。该方法接收的是一个数组，数组中的每个元素都是一个<code>Promise</code></p>
<p>对象。我们可以把这些<code>Promise</code>对象，看作是一个一个的异步任务。<code>all</code>方法会返回一个全新的<code>Promise</code>对象。当<code>all</code>方法内部所有的<code>Promise</code>对象都执行完毕后，这时我们才会获取到<code>all</code>方法所返回的新的<code>Promise</code>对象。该<code>Promise</code>对象获取到的结果是一个数组。在这个数组中包含了每个异步任务执行的结果。</p>
<p>需要注意的就是<code>all</code>方法中所有<code>Promise</code>对象都执行成功了，才表示成功，只要有一个失败了，那么<code>all</code>方法的执行就失败了。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> promise1 = <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="keyword">function</span>(<span class="params">resolve, reject</span>) &#123;</span><br><span class="line">           <span class="built_in">setTimeout</span>(<span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">               <span class="keyword">let</span> num = <span class="title class_">Math</span>.<span class="title function_">random</span>();</span><br><span class="line">               <span class="keyword">if</span> (num &gt; <span class="number">0.3</span>) &#123;</span><br><span class="line">                   <span class="title function_">resolve</span>(<span class="string">&#x27;成功了!&#x27;</span>)</span><br><span class="line">               &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                   <span class="title function_">reject</span>(<span class="string">&#x27;失败了1&#x27;</span>)</span><br><span class="line">               &#125;</span><br><span class="line">           &#125;, <span class="number">3000</span>)</span><br><span class="line">       &#125;)</span><br><span class="line">       <span class="keyword">let</span> promise2 = <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="keyword">function</span>(<span class="params">resolve, reject</span>) &#123;</span><br><span class="line">           <span class="built_in">setTimeout</span>(<span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">               <span class="keyword">let</span> num = <span class="title class_">Math</span>.<span class="title function_">random</span>();</span><br><span class="line">               <span class="keyword">if</span> (num &gt; <span class="number">0.3</span>) &#123;</span><br><span class="line">                   <span class="title function_">resolve</span>(<span class="string">&#x27;成功了!&#x27;</span>)</span><br><span class="line">               &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                   <span class="title function_">reject</span>(<span class="string">&#x27;失败了2&#x27;</span>)</span><br><span class="line">               &#125;</span><br><span class="line">           &#125;, <span class="number">3000</span>)</span><br><span class="line">       &#125;)</span><br><span class="line">     <span class="title class_">Promise</span>.<span class="title function_">all</span>([promise1, promise2]).<span class="title function_">then</span>(<span class="keyword">function</span>(<span class="params">data</span>) &#123;</span><br><span class="line">           <span class="variable language_">console</span>.<span class="title function_">log</span>(data);</span><br><span class="line">       &#125;)</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">&lt;!<span class="variable constant_">DOCTYPE</span> html&gt;</span><br><span class="line"><span class="language-xml"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;<span class="name">head</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">&quot;X-UA-Compatible&quot;</span> <span class="attr">content</span>=<span class="string">&quot;IE=edge&quot;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">&quot;viewport&quot;</span> <span class="attr">content</span>=<span class="string">&quot;width=device-width, initial-scale=1.0&quot;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Promise并行执行<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;/<span class="name">head</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;<span class="name">body</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="keyword">let</span> getJson = <span class="keyword">function</span> (<span class="params">url</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="keyword">let</span> p = <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="keyword">function</span> (<span class="params">resolve, reject</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="keyword">let</span> xhr = <span class="keyword">new</span> <span class="title class_">XMLHttpRequest</span>();</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          xhr.<span class="title function_">open</span>(<span class="string">&quot;GET&quot;</span>, url);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          xhr.<span class="property">onreadystatechange</span> = handler;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          xhr.<span class="property">responseType</span> = <span class="string">&quot;json&quot;</span>;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          xhr.<span class="title function_">setRequestHeader</span>(<span class="string">&quot;Accept&quot;</span>, <span class="string">&quot;application/json&quot;</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          xhr.<span class="title function_">send</span>();</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="keyword">function</span> <span class="title function_">handler</span>(<span class="params"></span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            <span class="keyword">if</span> (xhr.<span class="property">readyState</span> === <span class="number">4</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">              <span class="keyword">if</span> (xhr.<span class="property">status</span> == <span class="number">200</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                <span class="title function_">resolve</span>(<span class="variable language_">this</span>.<span class="property">response</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">              &#125; <span class="keyword">else</span> &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                <span class="title function_">reject</span>(<span class="keyword">new</span> <span class="title class_">Error</span>(<span class="variable language_">this</span>.<span class="property">statusText</span>));</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">              &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="keyword">return</span> p;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      &#125;;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="title class_">Promise</span>.<span class="title function_">all</span>([</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="title function_">getJson</span>(<span class="string">&quot;http://localhost:3005/products&quot;</span>),</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="title function_">getJson</span>(<span class="string">&quot;http://localhost:3005/cart&quot;</span>),</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="title function_">getJson</span>(<span class="string">&quot;http://localhost:3005/ddd&quot;</span>).<span class="title function_">catch</span>(<span class="function">() =&gt;</span> &#123;&#125;),</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      ])</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        .<span class="title function_">then</span>(<span class="function">(<span class="params">response</span>) =&gt;</span> &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="variable language_">console</span>.<span class="title function_">log</span>(response);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;)</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        .<span class="title function_">catch</span>(<span class="function">(<span class="params">err</span>) =&gt;</span> &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="variable language_">console</span>.<span class="title function_">log</span>(err);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">    </span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;/<span class="name">body</span>&gt;</span></span></span><br><span class="line"><span class="language-xml"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="6、Promise-race"><a href="#6、Promise-race" class="headerlink" title="6、Promise.race( )"></a>6、Promise.race( )</h2><p>与<code>all()</code>方法的区别是：</p>
<p><code>Promise.all( )</code>是等待所有任务结束后才会结束。</p>
<p>‘Promise.race( )’只要有一个任务完成就结束。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">&lt;!<span class="variable constant_">DOCTYPE</span> html&gt;</span><br><span class="line"><span class="language-xml"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;<span class="name">head</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">&quot;X-UA-Compatible&quot;</span> <span class="attr">content</span>=<span class="string">&quot;IE=edge&quot;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">&quot;viewport&quot;</span> <span class="attr">content</span>=<span class="string">&quot;width=device-width, initial-scale=1.0&quot;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Promise中race方法<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;/<span class="name">head</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;<span class="name">body</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="keyword">let</span> promise1 = <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="keyword">function</span> (<span class="params">resolve, reject</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="built_in">setTimeout</span>(<span class="keyword">function</span> (<span class="params"></span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="keyword">let</span> num = <span class="title class_">Math</span>.<span class="title function_">random</span>();</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="keyword">if</span> (num &gt; <span class="number">0.3</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            <span class="title function_">resolve</span>(<span class="string">&quot;成功了1!&quot;</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          &#125; <span class="keyword">else</span> &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            <span class="title function_">reject</span>(<span class="string">&quot;失败了1&quot;</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;, <span class="number">3000</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      &#125;);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="keyword">let</span> promise2 = <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="keyword">function</span> (<span class="params">resolve, reject</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="built_in">setTimeout</span>(<span class="keyword">function</span> (<span class="params"></span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="keyword">let</span> num = <span class="title class_">Math</span>.<span class="title function_">random</span>();</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="keyword">if</span> (num &gt; <span class="number">0.3</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            <span class="title function_">resolve</span>(<span class="string">&quot;成功了2!&quot;</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          &#125; <span class="keyword">else</span> &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            <span class="title function_">reject</span>(<span class="string">&quot;失败了2&quot;</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;, <span class="number">3000</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      &#125;);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="keyword">let</span> p = <span class="title class_">Promise</span>.<span class="title function_">race</span>([promise1, promise2])</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        .<span class="title function_">then</span>(<span class="keyword">function</span> (<span class="params">data</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="variable language_">console</span>.<span class="title function_">log</span>(data);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;)</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        .<span class="title function_">catch</span>(<span class="function">(<span class="params">err</span>) =&gt;</span> &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="variable language_">console</span>.<span class="title function_">log</span>(err);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">    </span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;/<span class="name">body</span>&gt;</span></span></span><br><span class="line"><span class="language-xml"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">&lt;!<span class="variable constant_">DOCTYPE</span> html&gt;</span><br><span class="line"><span class="language-xml"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;<span class="name">head</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">&quot;X-UA-Compatible&quot;</span> <span class="attr">content</span>=<span class="string">&quot;IE=edge&quot;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">&quot;viewport&quot;</span> <span class="attr">content</span>=<span class="string">&quot;width=device-width, initial-scale=1.0&quot;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Promise中race方法<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;/<span class="name">head</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;<span class="name">body</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="keyword">let</span> getJson = <span class="keyword">function</span> (<span class="params">url</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="keyword">let</span> p = <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="keyword">function</span> (<span class="params">resolve, reject</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="keyword">let</span> xhr = <span class="keyword">new</span> <span class="title class_">XMLHttpRequest</span>();</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          xhr.<span class="title function_">open</span>(<span class="string">&quot;GET&quot;</span>, url);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          xhr.<span class="property">onreadystatechange</span> = handler;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          xhr.<span class="property">responseType</span> = <span class="string">&quot;json&quot;</span>;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          xhr.<span class="title function_">setRequestHeader</span>(<span class="string">&quot;Accept&quot;</span>, <span class="string">&quot;application/json&quot;</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          xhr.<span class="title function_">send</span>();</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="keyword">function</span> <span class="title function_">handler</span>(<span class="params"></span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            <span class="keyword">if</span> (xhr.<span class="property">readyState</span> === <span class="number">4</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">              <span class="keyword">if</span> (xhr.<span class="property">status</span> == <span class="number">200</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                <span class="title function_">resolve</span>(<span class="variable language_">this</span>.<span class="property">response</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">              &#125; <span class="keyword">else</span> &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                <span class="title function_">reject</span>(<span class="keyword">new</span> <span class="title class_">Error</span>(<span class="variable language_">this</span>.<span class="property">statusText</span>));</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">              &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="keyword">return</span> p;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      &#125;;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="keyword">var</span> promise = <span class="title function_">getJson</span>(<span class="string">&quot;http://localhost:3005/products&quot;</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="keyword">const</span> timeout = <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="keyword">function</span> (<span class="params">resolve, reject</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> <span class="title function_">reject</span>(<span class="keyword">new</span> <span class="title class_">Error</span>(<span class="string">&quot;timeout&quot;</span>)), <span class="number">100</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      &#125;);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="title class_">Promise</span>.<span class="title function_">race</span>([promise, timeout])</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        .<span class="title function_">then</span>(<span class="function">(<span class="params">value</span>) =&gt;</span> &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="variable language_">console</span>.<span class="title function_">log</span>(value);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;)</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        .<span class="title function_">catch</span>(<span class="function">(<span class="params">error</span>) =&gt;</span> &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="variable language_">console</span>.<span class="title function_">log</span>(error);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">    </span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;/<span class="name">body</span>&gt;</span></span></span><br><span class="line"><span class="language-xml"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="7、Promise静态方法"><a href="#7、Promise静态方法" class="headerlink" title="7、Promise静态方法"></a>7、<code>Promise</code>静态方法</h2><p>在<code>Promise</code>中还有几个静态方法也会使用到。</p>
<p>第一个 是<code>Promise.resolve()</code></p>
<p>其作用就是将一个值，快速的转换成<code>Promise</code>对象。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="title class_">Promise</span>.<span class="title function_">resolve</span>(<span class="string">&#x27;foo&#x27;</span>).<span class="title function_">then</span>(<span class="keyword">function</span>(<span class="params">value</span>)&#123;</span><br><span class="line">    cosnole.<span class="title function_">log</span>(value)</span><br><span class="line">&#125;)<span class="comment">//返回一个成功的Promise对象</span></span><br></pre></td></tr></table></figure>

<p>第二个为<code>Promise.reject()</code>方法，该方法创建一个失败的<code>Promise</code>对象。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="title class_">Promise</span>.<span class="title function_">reject</span>(<span class="keyword">new</span> <span class="title class_">Error</span>(<span class="string">&#x27;rejected&#x27;</span>)).<span class="title function_">catch</span>(<span class="keyword">function</span>(<span class="params">error</span>)&#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(error)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h2 id="8、Promise执行顺序的问题"><a href="#8、Promise执行顺序的问题" class="headerlink" title="8、Promise执行顺序的问题"></a>8、Promise执行顺序的问题</h2><figure class="highlight js"><table><tr><td class="code"><pre><span class="line">&lt;!<span class="variable constant_">DOCTYPE</span> html&gt;</span><br><span class="line"><span class="language-xml"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;<span class="name">head</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">&quot;X-UA-Compatible&quot;</span> <span class="attr">content</span>=<span class="string">&quot;IE=edge&quot;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">&quot;viewport&quot;</span> <span class="attr">content</span>=<span class="string">&quot;width=device-width, initial-scale=1.0&quot;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Promise执行顺序问题<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;/<span class="name">head</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;<span class="name">body</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;start&quot;</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;setTimeout&quot;</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      &#125;, <span class="number">0</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="title class_">Promise</span>.<span class="title function_">resolve</span>()</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        .<span class="title function_">then</span>(<span class="function">() =&gt;</span> &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;promise&quot;</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;)</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        .<span class="title function_">then</span>(<span class="function">() =&gt;</span> &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;promise2&quot;</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;)</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        .<span class="title function_">then</span>(<span class="function">() =&gt;</span> &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;promise3&quot;</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;end&quot;</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">    </span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;/<span class="name">body</span>&gt;</span></span></span><br><span class="line"><span class="language-xml"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="9、模拟Promise对象"><a href="#9、模拟Promise对象" class="headerlink" title="9、模拟Promise对象"></a>9、模拟Promise对象</h2><h3 id="1、搭建基本结构"><a href="#1、搭建基本结构" class="headerlink" title="1、搭建基本结构"></a>1、搭建基本结构</h3><figure class="highlight js"><table><tr><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">         <span class="keyword">function</span> <span class="title function_">MyPromise</span>(<span class="params">task</span>)&#123;</span><br><span class="line">             <span class="keyword">let</span> that = <span class="variable language_">this</span>;</span><br><span class="line">             that.<span class="property">status</span>=<span class="string">&#x27;Pending&#x27;</span>;</span><br><span class="line">             <span class="keyword">function</span> <span class="title function_">resolve</span>(<span class="params"></span>)&#123;</span><br><span class="line"></span><br><span class="line">             &#125;</span><br><span class="line">             <span class="keyword">function</span> <span class="title function_">reject</span>(<span class="params"></span>)&#123;</span><br><span class="line"></span><br><span class="line">             &#125;</span><br><span class="line">             <span class="title function_">task</span>(resolve,reject);</span><br><span class="line"></span><br><span class="line">         &#125;</span><br><span class="line">         <span class="keyword">let</span> myPromise =<span class="keyword">new</span> <span class="title class_">MyPromise</span>(<span class="keyword">function</span>(<span class="params">resolve,reject</span>)&#123;</span><br><span class="line">             </span><br><span class="line"></span><br><span class="line">         &#125;)</span><br><span class="line">     &lt;/script&gt;</span><br></pre></td></tr></table></figure>

<h3 id="2、异常处理"><a href="#2、异常处理" class="headerlink" title="2、异常处理"></a>2、异常处理</h3><figure class="highlight js"><table><tr><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">     <span class="keyword">function</span> <span class="title function_">MyPromise</span>(<span class="params">task</span>) &#123;</span><br><span class="line">       <span class="keyword">let</span> that = <span class="variable language_">this</span>;</span><br><span class="line">       that.<span class="property">status</span> = <span class="string">&quot;Pending&quot;</span>;</span><br><span class="line">       <span class="keyword">function</span> <span class="title function_">resolve</span>(<span class="params"></span>) &#123;&#125;</span><br><span class="line">       <span class="keyword">function</span> <span class="title function_">reject</span>(<span class="params"></span>) &#123;</span><br><span class="line">         <span class="keyword">if</span> (that.<span class="property">status</span> === <span class="string">&quot;Pending&quot;</span>) &#123;</span><br><span class="line">           that.<span class="property">status</span> = <span class="string">&quot;Rejected&quot;</span>;</span><br><span class="line">           <span class="comment">//状态修改完成后，调用的是then 方法中处理失败的回调函数</span></span><br><span class="line">         &#125;</span><br><span class="line">       &#125;</span><br><span class="line">       <span class="keyword">try</span> &#123;</span><br><span class="line">         <span class="title function_">task</span>(resolve, reject);</span><br><span class="line">       &#125; <span class="keyword">catch</span> (e) &#123;</span><br><span class="line">         <span class="title function_">reject</span>(e);</span><br><span class="line">       &#125;</span><br><span class="line">     &#125;</span><br><span class="line">     <span class="title class_">MyPromise</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">then</span> = <span class="keyword">function</span> (<span class="params">onFulfilled, onRejected</span>) &#123;&#125;;</span><br><span class="line">     <span class="keyword">let</span> myPromise = <span class="keyword">new</span> <span class="title class_">MyPromise</span>(<span class="keyword">function</span> (<span class="params">resolve, reject</span>) &#123;&#125;);</span><br><span class="line">   &lt;/script&gt;</span><br></pre></td></tr></table></figure>

<h3 id="3、then方法处理与基本测试"><a href="#3、then方法处理与基本测试" class="headerlink" title="3、then方法处理与基本测试"></a>3、then方法处理与基本测试</h3><figure class="highlight js"><table><tr><td class="code"><pre><span class="line">&lt;!<span class="variable constant_">DOCTYPE</span> html&gt;</span><br><span class="line"><span class="language-xml"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;<span class="name">head</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">&quot;X-UA-Compatible&quot;</span> <span class="attr">content</span>=<span class="string">&quot;IE=edge&quot;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">&quot;viewport&quot;</span> <span class="attr">content</span>=<span class="string">&quot;width=device-width, initial-scale=1.0&quot;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>构建自己的Promise对象<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;/<span class="name">head</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;<span class="name">body</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="keyword">function</span> <span class="title function_">MyPromise</span>(<span class="params">task</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="keyword">let</span> that = <span class="variable language_">this</span>;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        that.<span class="property">status</span> = <span class="string">&quot;Pending&quot;</span>;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        that.<span class="property">value</span> = <span class="literal">undefined</span>;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        that.<span class="property">onResolvedCallbacks</span> = [];</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        that.<span class="property">onRejectedCallbacks</span> = [];</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="keyword">function</span> <span class="title function_">resolve</span>(<span class="params">value</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="keyword">if</span> (that.<span class="property">status</span> === <span class="string">&quot;Pending&quot;</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            that.<span class="property">status</span> = <span class="string">&quot;Resolved&quot;</span>;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            that.<span class="property">value</span> = value;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            that.<span class="property">onResolvedCallbacks</span>.<span class="title function_">forEach</span>(<span class="function">(<span class="params">item</span>) =&gt;</span> <span class="title function_">item</span>(that.<span class="property">value</span>));</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="keyword">function</span> <span class="title function_">reject</span>(<span class="params">reason</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="keyword">if</span> (that.<span class="property">status</span> === <span class="string">&quot;Pending&quot;</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            that.<span class="property">status</span> = <span class="string">&quot;Rejected&quot;</span>;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            that.<span class="property">value</span> = reason;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            <span class="comment">//状态修改完成后，调用的是then 方法中处理失败的回调函数</span></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            that.<span class="property">onRejectedCallbacks</span>.<span class="title function_">forEach</span>(<span class="function">(<span class="params">item</span>) =&gt;</span> <span class="title function_">item</span>(that.<span class="property">value</span>));</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="keyword">try</span> &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="title function_">task</span>(resolve, reject);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125; <span class="keyword">catch</span> (e) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="title function_">reject</span>(e);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="title class_">MyPromise</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">then</span> = <span class="keyword">function</span> (<span class="params">onFulfilled, onRejected</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="keyword">let</span> that = <span class="variable language_">this</span>;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        that.<span class="property">onResolvedCallbacks</span>.<span class="title function_">push</span>(onFulfilled);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        that.<span class="property">onRejectedCallbacks</span>.<span class="title function_">push</span>(onRejected);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      &#125;;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="keyword">let</span> myPromise = <span class="keyword">new</span> <span class="title class_">MyPromise</span>(<span class="keyword">function</span> (<span class="params">resolve, reject</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="built_in">setTimeout</span>(<span class="keyword">function</span> (<span class="params"></span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="keyword">let</span> num = <span class="title class_">Math</span>.<span class="title function_">random</span>();</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="keyword">if</span> (num &gt; <span class="number">0.3</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            <span class="title function_">resolve</span>(<span class="string">&quot;成功了&quot;</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          &#125; <span class="keyword">else</span> &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            <span class="title function_">reject</span>(<span class="string">&quot;失败了&quot;</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;, <span class="number">3000</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      &#125;);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      myPromise.<span class="title function_">then</span>(</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="keyword">function</span> (<span class="params">value</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="variable language_">console</span>.<span class="title function_">log</span>(value);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="keyword">function</span> (<span class="params">reason</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="variable language_">console</span>.<span class="title function_">log</span>(reason);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      );</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">    </span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;/<span class="name">body</span>&gt;</span></span></span><br><span class="line"><span class="language-xml"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="4、完善操作"><a href="#4、完善操作" class="headerlink" title="4、完善操作"></a>4、完善操作</h3><figure class="highlight js"><table><tr><td class="code"><pre><span class="line">&lt;!<span class="variable constant_">DOCTYPE</span> html&gt;</span><br><span class="line"><span class="language-xml"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;<span class="name">head</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">&quot;X-UA-Compatible&quot;</span> <span class="attr">content</span>=<span class="string">&quot;IE=edge&quot;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">&quot;viewport&quot;</span> <span class="attr">content</span>=<span class="string">&quot;width=device-width, initial-scale=1.0&quot;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>构建自己的Promise对象<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;/<span class="name">head</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;<span class="name">body</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="keyword">function</span> <span class="title function_">MyPromise</span>(<span class="params">task</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="keyword">let</span> that = <span class="variable language_">this</span>;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        that.<span class="property">status</span> = <span class="string">&quot;Pending&quot;</span>;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        that.<span class="property">value</span> = <span class="literal">undefined</span>;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        that.<span class="property">onResolvedCallbacks</span> = [];</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        that.<span class="property">onRejectedCallbacks</span> = [];</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="keyword">function</span> <span class="title function_">resolve</span>(<span class="params">value</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="keyword">if</span> (that.<span class="property">status</span> === <span class="string">&quot;Pending&quot;</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            that.<span class="property">status</span> = <span class="string">&quot;Resolved&quot;</span>;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            that.<span class="property">value</span> = value;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            that.<span class="property">onResolvedCallbacks</span>.<span class="title function_">forEach</span>(<span class="function">(<span class="params">item</span>) =&gt;</span> <span class="title function_">item</span>(that.<span class="property">value</span>));</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="keyword">function</span> <span class="title function_">reject</span>(<span class="params">reason</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="keyword">if</span> (that.<span class="property">status</span> === <span class="string">&quot;Pending&quot;</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            that.<span class="property">status</span> = <span class="string">&quot;Rejected&quot;</span>;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            that.<span class="property">value</span> = reason;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            <span class="comment">//状态修改完成后，调用的是then 方法中处理失败的回调函数</span></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            that.<span class="property">onRejectedCallbacks</span>.<span class="title function_">forEach</span>(<span class="function">(<span class="params">item</span>) =&gt;</span> <span class="title function_">item</span>(that.<span class="property">value</span>));</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="keyword">try</span> &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="title function_">task</span>(resolve, reject);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125; <span class="keyword">catch</span> (e) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="title function_">reject</span>(e);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="title class_">MyPromise</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">then</span> = <span class="keyword">function</span> (<span class="params">onFulfilled, onRejected</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="keyword">let</span> that = <span class="variable language_">this</span>;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="keyword">if</span> (that.<span class="property">status</span> === <span class="string">&quot;Resolved&quot;</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="title function_">onFulfilled</span>(that.<span class="property">value</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="keyword">if</span> (that.<span class="property">status</span> === <span class="string">&quot;Rejected&quot;</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="title function_">onRejected</span>(that.<span class="property">value</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        that.<span class="property">onResolvedCallbacks</span>.<span class="title function_">push</span>(onFulfilled);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        that.<span class="property">onRejectedCallbacks</span>.<span class="title function_">push</span>(onRejected);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      &#125;;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="keyword">let</span> myPromise = <span class="keyword">new</span> <span class="title class_">MyPromise</span>(<span class="keyword">function</span> (<span class="params">resolve, reject</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="comment">// setTimeout(function () &#123;</span></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="comment">//   let num = Math.random();</span></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="comment">//   if (num &gt; 0.3) &#123;</span></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="comment">//     resolve(&quot;成功了&quot;);</span></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="comment">//   &#125; else &#123;</span></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="comment">//     reject(&quot;失败了&quot;);</span></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="comment">//   &#125;</span></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="comment">// &#125;, 3000);</span></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="title function_">resolve</span>(<span class="string">&quot;成功了&quot;</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      &#125;);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      myPromise.<span class="title function_">then</span>(</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="keyword">function</span> (<span class="params">value</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="variable language_">console</span>.<span class="title function_">log</span>(value);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        <span class="keyword">function</span> (<span class="params">reason</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">          <span class="variable language_">console</span>.<span class="title function_">log</span>(reason);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      );</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">    </span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;/<span class="name">body</span>&gt;</span></span></span><br><span class="line"><span class="language-xml"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h1 id="三、async函数"><a href="#三、async函数" class="headerlink" title="三、async函数"></a>三、async函数</h1><h2 id="1、常见异步编程方式"><a href="#1、常见异步编程方式" class="headerlink" title="1、常见异步编程方式"></a>1、常见异步编程方式</h2><h4 id="1-2-1-回调函数"><a href="#1-2-1-回调函数" class="headerlink" title="1.2.1 回调函数"></a>1.2.1 回调函数</h4><p>JavaScript 语言对异步编程的实现，就是回调函数。<strong>所谓回调函数，就是把任务的第二段单独写在一个函数里面，等到重新执行这个任务的时候，就直接调用这个函数。</strong>它的英语名字 callback，直译过来就是”重新调用”。 </p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">fs.<span class="title function_">readFile</span>(<span class="string">&#x27;/etc/passwd&#x27;</span>, <span class="keyword">function</span> (<span class="params">err, data</span>) &#123;</span><br><span class="line">  <span class="keyword">if</span> (err) <span class="keyword">throw</span> err;</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(data);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>上面代码中，readFile 函数的第二个参数，就是回调函数，也就是任务的第二段。等到操作系统返回了 &#x2F;etc&#x2F;passwd 这个文件以后，回调函数才会执行。 </p>
<h4 id="1-2-2-Promise对象"><a href="#1-2-2-Promise对象" class="headerlink" title="1.2.2 Promise对象"></a>1.2.2 Promise对象</h4><p>回调函数本身并没有问题，它的问题出现在多个回调函数嵌套。假定读取A文件之后，再读取B文件，代码如下。 </p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">fs.<span class="title function_">readFile</span>(fileA, <span class="keyword">function</span> (<span class="params">err, data</span>) &#123;</span><br><span class="line">  fs.<span class="title function_">readFile</span>(fileB, <span class="keyword">function</span> (<span class="params">err, data</span>) &#123;</span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">  &#125;);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>不难想象，如果依次读取多个文件，就会出现多重嵌套 .这样就产生了，我们前面讲解的回调地狱问题。</p>
<p>而Promise对象就是为了解决这个问题。</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="title function_">readFile</span>(fileA)</span><br><span class="line">.<span class="title function_">then</span>(<span class="keyword">function</span>(<span class="params">data</span>)&#123;</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(data.<span class="title function_">toString</span>());</span><br><span class="line">&#125;)</span><br><span class="line">.<span class="title function_">then</span>(<span class="keyword">function</span>(<span class="params"></span>)&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="title function_">readFile</span>(fileB);</span><br><span class="line">&#125;)</span><br><span class="line">.<span class="title function_">then</span>(<span class="keyword">function</span>(<span class="params">data</span>)&#123;</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(data.<span class="title function_">toString</span>());</span><br><span class="line">&#125;)</span><br><span class="line">.<span class="title function_">catch</span>(<span class="keyword">function</span>(<span class="params">err</span>) &#123;</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(err);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>通过Promise解决了回调地狱的问题。</p>
<h4 id="1-2-3-Generator函数"><a href="#1-2-3-Generator函数" class="headerlink" title="1.2.3 Generator函数"></a>1.2.3 Generator函数</h4><p>Generator函数,就是一个封装的异步任务，或者说是异步任务的容器。异步操作需要暂停的地方，都用到yield语句。</p>
<p>下面的案例是前面用Generator函数封装的AJAX的异步操作。</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">function</span>* <span class="title function_">main</span>(<span class="params"></span>) &#123;</span><br><span class="line">  <span class="keyword">let</span> result = <span class="keyword">yield</span> <span class="title function_">request</span>(<span class="string">&quot;http://xxx.com/api&quot;</span>);</span><br><span class="line">  <span class="keyword">let</span> resp = <span class="title class_">JSON</span>.<span class="title function_">parse</span>(result);</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(resp.<span class="property">value</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">request</span>(<span class="params">url</span>) &#123;</span><br><span class="line">  <span class="title function_">makeAjaxCall</span>(url, <span class="keyword">function</span>(<span class="params">response</span>)&#123;</span><br><span class="line">    it.<span class="title function_">next</span>(response);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> it = <span class="title function_">main</span>();</span><br><span class="line">it.<span class="title function_">next</span>();</span><br></pre></td></tr></table></figure>

<h2 id="2、async函数"><a href="#2、async函数" class="headerlink" title="2、async函数"></a>2、async函数</h2><h3 id="2-1-基本用法"><a href="#2-1-基本用法" class="headerlink" title="2.1 基本用法"></a>2.1 基本用法</h3><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">async</span> <span class="keyword">function</span> <span class="title function_">test</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">let</span> result = <span class="keyword">await</span> <span class="title class_">Math</span>.<span class="title function_">random</span>();</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(result);         </span><br><span class="line">&#125;</span><br><span class="line"><span class="title function_">test</span>();</span><br></pre></td></tr></table></figure>

<p>async: 表示函数中有异步操作,await 必须出现在 async 函数内部，不能单独使用。 </p>
<p>await: 表示紧跟在后面的表达式需要等待结果。一般情况下await后面跟的是一个耗时的操作或者一个异步的操作。</p>
<h3 id="2-2-使用方式"><a href="#2-2-使用方式" class="headerlink" title="2.2 使用方式"></a>2.2 使用方式</h3><figure class="highlight js"><table><tr><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">    <span class="keyword">function</span> <span class="title function_">sleep</span>(<span class="params">second</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="keyword">function</span> (<span class="params">resolve, reject</span>) &#123;</span><br><span class="line">        <span class="built_in">setTimeout</span>(<span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">          <span class="keyword">let</span> num = <span class="title class_">Math</span>.<span class="title function_">random</span>();</span><br><span class="line">          <span class="keyword">if</span> (num &gt; <span class="number">0.8</span>) &#123;</span><br><span class="line">            <span class="title function_">resolve</span>(<span class="string">&quot;成功了&quot;</span>);</span><br><span class="line">          &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="title function_">reject</span>(<span class="string">&quot;失败了&quot;</span>);</span><br><span class="line">          &#125;</span><br><span class="line">        &#125;, second);</span><br><span class="line">      &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">async</span> <span class="keyword">function</span> <span class="title function_">awaitDemo</span>(<span class="params"></span>) &#123;</span><br><span class="line">      <span class="keyword">let</span> result = <span class="keyword">await</span> <span class="title function_">sleep</span>(<span class="number">3000</span>);</span><br><span class="line">      <span class="keyword">return</span> result;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">awaitDemo</span>()</span><br><span class="line">      .<span class="title function_">then</span>(<span class="keyword">function</span> (<span class="params">data</span>) &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;data=&quot;</span>, data);</span><br><span class="line">      &#125;)</span><br><span class="line">      .<span class="title function_">catch</span>(<span class="keyword">function</span> (<span class="params">err</span>) &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;error=&quot;</span>, err);</span><br><span class="line">      &#125;);</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;执行其它的代码&quot;</span>);</span><br><span class="line">  &lt;/script&gt;</span><br></pre></td></tr></table></figure>

<h3 id="2-3-处理异步请求"><a href="#2-3-处理异步请求" class="headerlink" title="2.3 处理异步请求"></a>2.3 处理异步请求</h3><figure class="highlight js"><table><tr><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">      <span class="keyword">let</span> getJson = <span class="keyword">function</span> (<span class="params">url</span>) &#123;</span><br><span class="line">        <span class="keyword">let</span> p = <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="keyword">function</span> (<span class="params">resolve, reject</span>) &#123;</span><br><span class="line">          <span class="keyword">let</span> xhr = <span class="keyword">new</span> <span class="title class_">XMLHttpRequest</span>();</span><br><span class="line">          xhr.<span class="title function_">open</span>(<span class="string">&quot;GET&quot;</span>, url);</span><br><span class="line">          xhr.<span class="property">onreadystatechange</span> = handler;</span><br><span class="line">          xhr.<span class="property">responseType</span> = <span class="string">&quot;json&quot;</span>;</span><br><span class="line">          xhr.<span class="title function_">setRequestHeader</span>(<span class="string">&quot;Accept&quot;</span>, <span class="string">&quot;application/json&quot;</span>);</span><br><span class="line">          xhr.<span class="title function_">send</span>();</span><br><span class="line">          <span class="keyword">function</span> <span class="title function_">handler</span>(<span class="params"></span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> (xhr.<span class="property">readyState</span> === <span class="number">4</span>) &#123;</span><br><span class="line">              <span class="keyword">if</span> (xhr.<span class="property">status</span> == <span class="number">200</span>) &#123;</span><br><span class="line">                <span class="title function_">resolve</span>(<span class="variable language_">this</span>.<span class="property">response</span>);</span><br><span class="line">              &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="title function_">reject</span>(<span class="keyword">new</span> <span class="title class_">Error</span>(<span class="variable language_">this</span>.<span class="property">statusText</span>));</span><br><span class="line">              &#125;</span><br><span class="line">            &#125;</span><br><span class="line">          &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">        <span class="keyword">return</span> p;</span><br><span class="line">      &#125;;</span><br><span class="line">      <span class="keyword">async</span> <span class="keyword">function</span> <span class="title function_">getAjax</span>(<span class="params"></span>) &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">          <span class="keyword">let</span> result = <span class="keyword">await</span> <span class="title function_">getJson</span>(<span class="string">&quot;http://localhost:3005/products&quot;</span>);</span><br><span class="line">          <span class="variable language_">console</span>.<span class="title function_">log</span>(result);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (err) &#123;</span><br><span class="line">          <span class="variable language_">console</span>.<span class="title function_">log</span>(err);</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="title function_">getAjax</span>();</span><br><span class="line">    &lt;/script&gt;</span><br></pre></td></tr></table></figure>

<h3 id="2-4-请求依赖关系的处理"><a href="#2-4-请求依赖关系的处理" class="headerlink" title="2.4 请求依赖关系的处理"></a>2.4 请求依赖关系的处理</h3><figure class="highlight js"><table><tr><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">    <span class="keyword">function</span> <span class="title function_">sleep</span>(<span class="params">second, param</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">          <span class="title function_">resolve</span>(param);</span><br><span class="line">        &#125;, second);</span><br><span class="line">      &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">async</span> <span class="keyword">function</span> <span class="title function_">test</span>(<span class="params"></span>) &#123;</span><br><span class="line">      <span class="keyword">let</span> result1 = <span class="keyword">await</span> <span class="title function_">sleep</span>(<span class="number">2000</span>, <span class="string">&quot;req01&quot;</span>);</span><br><span class="line">      <span class="keyword">let</span> result2 = <span class="keyword">await</span> <span class="title function_">sleep</span>(<span class="number">1000</span>, <span class="string">&quot;req02&quot;</span> + result1);</span><br><span class="line">      <span class="keyword">let</span> result3 = <span class="keyword">await</span> <span class="title function_">sleep</span>(<span class="number">500</span>, <span class="string">&quot;req03&quot;</span> + result2);</span><br><span class="line">      <span class="variable language_">console</span>.<span class="title function_">log</span>(result1, result2, result3);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">test</span>();</span><br><span class="line">  &lt;/script&gt;</span><br></pre></td></tr></table></figure>

<h3 id="2-5-并且处理的问题"><a href="#2-5-并且处理的问题" class="headerlink" title="2.5 并且处理的问题"></a>2.5 并且处理的问题</h3><figure class="highlight js"><table><tr><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">     <span class="keyword">let</span> getJSON = <span class="keyword">function</span> (<span class="params">url</span>) &#123;</span><br><span class="line">       <span class="keyword">let</span> p = <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="keyword">function</span> (<span class="params">resolve, reject</span>) &#123;</span><br><span class="line">         <span class="keyword">let</span> xhr = <span class="keyword">new</span> <span class="title class_">XMLHttpRequest</span>();</span><br><span class="line">         xhr.<span class="title function_">open</span>(<span class="string">&quot;GET&quot;</span>, url);</span><br><span class="line">         xhr.<span class="property">onreadystatechange</span> = handler;</span><br><span class="line">         xhr.<span class="property">responseType</span> = <span class="string">&quot;json&quot;</span>;</span><br><span class="line">         xhr.<span class="title function_">setRequestHeader</span>(<span class="string">&quot;Accept&quot;</span>, <span class="string">&quot;application/json&quot;</span>);</span><br><span class="line">         xhr.<span class="title function_">send</span>();</span><br><span class="line"></span><br><span class="line">         <span class="keyword">function</span> <span class="title function_">handler</span>(<span class="params"></span>) &#123;</span><br><span class="line">           <span class="keyword">if</span> (xhr.<span class="property">readyState</span> === <span class="number">4</span>) &#123;</span><br><span class="line">             <span class="keyword">if</span> (<span class="variable language_">this</span>.<span class="property">status</span> === <span class="number">200</span>) &#123;</span><br><span class="line">               <span class="title function_">resolve</span>(<span class="variable language_">this</span>.<span class="property">response</span>);</span><br><span class="line">             &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">               <span class="title function_">reject</span>(<span class="keyword">new</span> <span class="title class_">Error</span>(<span class="variable language_">this</span>.<span class="property">statusText</span>));</span><br><span class="line">             &#125;</span><br><span class="line">           &#125;</span><br><span class="line">         &#125;</span><br><span class="line">       &#125;);</span><br><span class="line">       <span class="comment">//返回Promise对象</span></span><br><span class="line">       <span class="keyword">return</span> p;</span><br><span class="line">     &#125;;</span><br><span class="line">     <span class="keyword">async</span> <span class="keyword">function</span> <span class="title function_">getAJAX</span>(<span class="params"></span>) &#123;</span><br><span class="line">       <span class="comment">// try &#123;</span></span><br><span class="line">       <span class="comment">//   let result = await getJSON(&quot;http://localhost:3005/products&quot;);</span></span><br><span class="line">       <span class="comment">//   let result1 = await getJSON(&quot;http://localhost:3005/products&quot;);</span></span><br><span class="line">       <span class="comment">//   let result2 = await getJSON(&quot;http://localhost:3005/products&quot;);</span></span><br><span class="line">       <span class="comment">//   console.log(result, result1, result2);</span></span><br><span class="line">       <span class="comment">//   console.log(&quot;clear the loading~&quot;); //通过这一句代码模拟隐藏loading图片</span></span><br><span class="line">       <span class="comment">// &#125; catch (e) &#123;</span></span><br><span class="line">       <span class="comment">//   console.log(e);</span></span><br><span class="line">       <span class="comment">// &#125;</span></span><br><span class="line">       <span class="keyword">try</span> &#123;</span><br><span class="line">         <span class="keyword">let</span> result = <span class="title function_">getJSON</span>(<span class="string">&quot;http://localhost:3005/products&quot;</span>);</span><br><span class="line">         <span class="keyword">let</span> result1 = <span class="title function_">getJSON</span>(<span class="string">&quot;http://localhost:3005/products&quot;</span>);</span><br><span class="line">         <span class="keyword">let</span> result2 = <span class="title function_">getJSON</span>(<span class="string">&quot;http://localhost:3005/products&quot;</span>);</span><br><span class="line">         <span class="keyword">let</span> p = <span class="keyword">await</span> <span class="title class_">Promise</span>.<span class="title function_">all</span>([result, result1, result2]);</span><br><span class="line">         <span class="variable language_">console</span>.<span class="title function_">log</span>(p);</span><br><span class="line">         <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;clear the loading~&quot;</span>);</span><br><span class="line">       &#125; <span class="keyword">catch</span> (e) &#123;</span><br><span class="line">         <span class="variable language_">console</span>.<span class="title function_">log</span>(e);</span><br><span class="line">       &#125;</span><br><span class="line">     &#125;</span><br><span class="line">     <span class="title function_">getAJAX</span>();</span><br><span class="line">   &lt;/script&gt;</span><br></pre></td></tr></table></figure>

</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="http://example.com">Justic</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://example.com/2022/07/13/JavaScript/JavaScript%20%E9%9D%A2%E8%AF%95%E7%B2%BE%E8%AE%B2/JavaScript%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B/">http://example.com/2022/07/13/JavaScript/JavaScript 面试精讲/JavaScript异步编程/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://justicc.top/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://example.com" target="_blank">Justic</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/JavaScript/">JavaScript</a></div><div class="post_share"><div class="social-share" data-image="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/j3/wallhaven-j3qq15.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/img/wechat.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="/img/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/img/alipay.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="/img/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2022/07/13/JavaScript/JavaScript%20%E9%9D%A2%E8%AF%95%E7%B2%BE%E8%AE%B2/JavaScript%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/"><img class="prev-cover" src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/3z/wallhaven-3zgz2y.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">JavaScript 性能优化</div></div></a></div><div class="next-post pull-right"><a href="/2022/07/13/JavaScript/JavaScript%20%E9%9D%A2%E8%AF%95%E7%B2%BE%E8%AE%B2/%E6%A8%A1%E5%9D%97%E5%8C%96/"><img class="next-cover" src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/m9/wallhaven-m9y289.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">JavaScript 模块化</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2022/07/07/JavaScript/JavaScript%E5%BC%95%E6%93%8E/" title="JavaScript 引擎"><img class="cover" src= "" data-lazy-src="https://pic1.zhimg.com/v2-4dce785ff4595de55623611ab0055d33_1440w.jpg?source=172ae18b" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-07-07</div><div class="title">JavaScript 引擎</div></div></a></div><div><a href="/2022/07/22/JavaScript/JavaScript%E5%87%BD%E6%95%B0this%E6%8C%87%E5%90%91/JavaScript%E5%87%BD%E6%95%B0this%E6%8C%87%E5%90%91/" title="JavaScript函数this指向"><img class="cover" src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/k7/wallhaven-k7jmg6.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-07-22</div><div class="title">JavaScript函数this指向</div></div></a></div><div><a href="/2022/07/13/JavaScript/JavaScript%20%E9%9D%A2%E8%AF%95%E7%B2%BE%E8%AE%B2/JavaScript%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/" title="JavaScript 性能优化"><img class="cover" src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/3z/wallhaven-3zgz2y.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-07-13</div><div class="title">JavaScript 性能优化</div></div></a></div><div><a href="/2022/07/13/JavaScript/JavaScript%20%E9%9D%A2%E8%AF%95%E7%B2%BE%E8%AE%B2/%E6%A8%A1%E5%9D%97%E5%8C%96/" title="JavaScript 模块化"><img class="cover" src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/m9/wallhaven-m9y289.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-07-13</div><div class="title">JavaScript 模块化</div></div></a></div><div><a href="/2022/08/08/JavaScript/JavaScript%E5%87%BD%E6%95%B0%E5%A2%9E%E5%BC%BA%E7%9F%A5%E8%AF%86/index/" title="JavaScript函数增强知识"><img class="cover" src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/28/wallhaven-2881yx.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-08</div><div class="title">JavaScript函数增强知识</div></div></a></div><div><a href="/2022/07/13/JavaScript/JavaScript%20%E9%9D%A2%E8%AF%95%E7%B2%BE%E8%AE%B2/JavaScript%E9%9D%A2%E8%AF%95%E7%B2%BE%E8%AE%B2/" title="JavaScript 精讲"><img class="cover" src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/z8/wallhaven-z82evv.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-07-13</div><div class="title">JavaScript 精讲</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "" data-lazy-src="https://portrait.gitee.com/uploads/avatars/user/2982/8948190_JIAXInT_1624177607.png!avatar200" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Justic</div><div class="author-info__description">最是人间留不住 朱颜辞镜花辞树</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">22</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">2</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">3</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/xxxxxx"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%B8%80%E3%80%81Generator%E5%87%BD%E6%95%B0"><span class="toc-text">一、Generator函数</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%E3%80%81%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8"><span class="toc-text">1、基本使用</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2%E3%80%81next%E6%96%B9%E6%B3%95%E5%8F%82%E6%95%B0"><span class="toc-text">2、next方法参数</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3%E3%80%81for%E2%80%A6of%E5%BE%AA%E7%8E%AF"><span class="toc-text">3、for…of循环</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4%E3%80%81yield-%E8%AF%AD%E5%8F%A5"><span class="toc-text">4、yield* 语句</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5%E3%80%81%E5%85%B3%E4%BA%8EGenerator%E5%87%BD%E6%95%B0%E4%B8%AD%E7%9A%84this%E9%97%AE%E9%A2%98"><span class="toc-text">5、关于Generator函数中的this问题</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6%E3%80%81Generator%E5%87%BD%E6%95%B0%E5%BA%94%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="toc-text">6、Generator函数应用场景</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#6-1-%E7%8A%B6%E6%80%81%E5%A4%84%E7%90%86"><span class="toc-text">6.1 状态处理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-2-%E5%BC%82%E6%AD%A5%E5%A4%84%E7%90%86"><span class="toc-text">6.2 异步处理</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BA%8C%E3%80%81Promise%E5%AF%B9%E8%B1%A1"><span class="toc-text">二、Promise对象</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%E3%80%81Promise%E5%AE%9A%E4%B9%89"><span class="toc-text">1、Promise定义</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-1-%E5%9B%9E%E8%B0%83%E5%9C%B0%E7%8B%B1%E9%97%AE%E9%A2%98"><span class="toc-text">1.1 回调地狱问题</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%90%8C%E6%AD%A5%E6%A8%A1%E5%BC%8F"><span class="toc-text">同步模式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BC%82%E6%AD%A5%E6%A8%A1%E5%BC%8F"><span class="toc-text">异步模式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise%E6%A6%82%E5%BF%B5%E4%B8%8E%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8"><span class="toc-text">Promise概念与基本使用</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-%E4%BD%BF%E7%94%A8Promise%E5%B0%81%E8%A3%85AJAX%E6%93%8D%E4%BD%9C"><span class="toc-text">2 使用Promise封装AJAX操作</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3%E3%80%81Promise%E9%93%BE%E5%BC%8F%E8%B0%83%E7%94%A8"><span class="toc-text">3、Promise链式调用</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4%E3%80%81Promise%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86"><span class="toc-text">4、Promise异常处理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5%E3%80%81Promise%E5%B9%B6%E8%A1%8C%E6%89%A7%E8%A1%8C"><span class="toc-text">5、Promise并行执行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6%E3%80%81Promise-race"><span class="toc-text">6、Promise.race( )</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#7%E3%80%81Promise%E9%9D%99%E6%80%81%E6%96%B9%E6%B3%95"><span class="toc-text">7、Promise静态方法</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#8%E3%80%81Promise%E6%89%A7%E8%A1%8C%E9%A1%BA%E5%BA%8F%E7%9A%84%E9%97%AE%E9%A2%98"><span class="toc-text">8、Promise执行顺序的问题</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#9%E3%80%81%E6%A8%A1%E6%8B%9FPromise%E5%AF%B9%E8%B1%A1"><span class="toc-text">9、模拟Promise对象</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%E3%80%81%E6%90%AD%E5%BB%BA%E5%9F%BA%E6%9C%AC%E7%BB%93%E6%9E%84"><span class="toc-text">1、搭建基本结构</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%E3%80%81%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86"><span class="toc-text">2、异常处理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%E3%80%81then%E6%96%B9%E6%B3%95%E5%A4%84%E7%90%86%E4%B8%8E%E5%9F%BA%E6%9C%AC%E6%B5%8B%E8%AF%95"><span class="toc-text">3、then方法处理与基本测试</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4%E3%80%81%E5%AE%8C%E5%96%84%E6%93%8D%E4%BD%9C"><span class="toc-text">4、完善操作</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%B8%89%E3%80%81async%E5%87%BD%E6%95%B0"><span class="toc-text">三、async函数</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%E3%80%81%E5%B8%B8%E8%A7%81%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B%E6%96%B9%E5%BC%8F"><span class="toc-text">1、常见异步编程方式</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-2-1-%E5%9B%9E%E8%B0%83%E5%87%BD%E6%95%B0"><span class="toc-text">1.2.1 回调函数</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#1-2-2-Promise%E5%AF%B9%E8%B1%A1"><span class="toc-text">1.2.2 Promise对象</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#1-2-3-Generator%E5%87%BD%E6%95%B0"><span class="toc-text">1.2.3 Generator函数</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2%E3%80%81async%E5%87%BD%E6%95%B0"><span class="toc-text">2、async函数</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#2-1-%E5%9F%BA%E6%9C%AC%E7%94%A8%E6%B3%95"><span class="toc-text">2.1 基本用法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-%E4%BD%BF%E7%94%A8%E6%96%B9%E5%BC%8F"><span class="toc-text">2.2 使用方式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-3-%E5%A4%84%E7%90%86%E5%BC%82%E6%AD%A5%E8%AF%B7%E6%B1%82"><span class="toc-text">2.3 处理异步请求</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-4-%E8%AF%B7%E6%B1%82%E4%BE%9D%E8%B5%96%E5%85%B3%E7%B3%BB%E7%9A%84%E5%A4%84%E7%90%86"><span class="toc-text">2.4 请求依赖关系的处理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-5-%E5%B9%B6%E4%B8%94%E5%A4%84%E7%90%86%E7%9A%84%E9%97%AE%E9%A2%98"><span class="toc-text">2.5 并且处理的问题</span></a></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2022/11/09/JavaScript/ES6%E6%96%B0%E7%89%B9%E6%80%A7/index/" title="ES6新特性"><img src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/m9/wallhaven-m9y289.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="ES6新特性"/></a><div class="content"><a class="title" href="/2022/11/09/JavaScript/ES6%E6%96%B0%E7%89%B9%E6%80%A7/index/" title="ES6新特性">ES6新特性</a><time datetime="2022-11-09T12:55:33.000Z" title="发表于 2022-11-09 20:55:33">2022-11-09</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/10/20/Vue/Vue%20%E5%93%8D%E5%BA%94%E5%BC%8F%E8%A7%A3%E6%9E%90/Vue%E5%93%8D%E5%BA%94%E5%BC%8F%E8%A7%A3%E6%9E%90/" title="Vue 响应式解析"><img src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/z8/wallhaven-z82evv.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Vue 响应式解析"/></a><div class="content"><a class="title" href="/2022/10/20/Vue/Vue%20%E5%93%8D%E5%BA%94%E5%BC%8F%E8%A7%A3%E6%9E%90/Vue%E5%93%8D%E5%BA%94%E5%BC%8F%E8%A7%A3%E6%9E%90/" title="Vue 响应式解析">Vue 响应式解析</a><time datetime="2022-10-20T12:05:37.000Z" title="发表于 2022-10-20 20:05:37">2022-10-20</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/08/08/JavaScript/JavaScript%E5%8E%9F%E5%9E%8B%E5%92%8C%E5%8E%9F%E5%9E%8B%E9%93%BE/index/" title="JavaScript原型和原型链"><img src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/z8/wallhaven-z82evv.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JavaScript原型和原型链"/></a><div class="content"><a class="title" href="/2022/08/08/JavaScript/JavaScript%E5%8E%9F%E5%9E%8B%E5%92%8C%E5%8E%9F%E5%9E%8B%E9%93%BE/index/" title="JavaScript原型和原型链">JavaScript原型和原型链</a><time datetime="2022-08-08T09:08:31.000Z" title="发表于 2022-08-08 17:08:31">2022-08-08</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/08/08/JavaScript/JavaScript%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%A2%9E%E5%BC%BA%E7%9F%A5%E8%AF%86/index/" title="JavaScript对象的增强知识"><img src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/j3/wallhaven-j3qq15.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JavaScript对象的增强知识"/></a><div class="content"><a class="title" href="/2022/08/08/JavaScript/JavaScript%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%A2%9E%E5%BC%BA%E7%9F%A5%E8%AF%86/index/" title="JavaScript对象的增强知识">JavaScript对象的增强知识</a><time datetime="2022-08-08T07:43:36.000Z" title="发表于 2022-08-08 15:43:36">2022-08-08</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/08/08/JavaScript/JavaScript%E5%87%BD%E6%95%B0%E5%A2%9E%E5%BC%BA%E7%9F%A5%E8%AF%86/index/" title="JavaScript函数增强知识"><img src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/28/wallhaven-2881yx.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JavaScript函数增强知识"/></a><div class="content"><a class="title" href="/2022/08/08/JavaScript/JavaScript%E5%87%BD%E6%95%B0%E5%A2%9E%E5%BC%BA%E7%9F%A5%E8%AF%86/index/" title="JavaScript函数增强知识">JavaScript函数增强知识</a><time datetime="2022-08-08T03:25:40.000Z" title="发表于 2022-08-08 11:25:40">2022-08-08</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/j3/wallhaven-j3qq15.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By Justic</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a><img src= "" data-lazy-src="https://static.dy208.cn/o_1dfilp8ruo521thr1hvf18ji17soa.png">
<a href="http://www.beian.miit.gov.cn/"  style="color:#f72b07" target="_blank">晋ICP备2021014440号-2</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="chat_btn" type="button" title="聊天"><i class="fas fa-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: 'KgIigedIwh0GobYsWWfPMEdO-gzGzoHsz',
      appKey: 'WpJEQP22asTau19i2tq1yQhU',
      avatar: 'justic',
      serverURLs: '',
      emojiMaps: "",
      path: window.location.pathname,
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !false) {
  if (false) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script></div><div class="aplayer no-destroy" data-id="5076309057" data-server="netease" data-type="playlist" data-fixed="true" data-autoplay="true" data-lrcType="-1"> </div><script id="canvas_nest" defer="defer" color="0,0,255" opacity="0.7" zIndex="-1" count="99" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-nest.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = false;
POWERMODE.mobile = true;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-show-text" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-show-text.min.js" data-mobile="true" data-text="富强,民主,文明,和谐,平等,公正,法治,爱国,敬业,诚信,友善" data-fontsize="15px" data-random="true" async="async"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/metingjs/dist/Meting.min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><!-- hexo injector body_end start --><script data-pjax>
  function butterfly_clock_anzhiyu_injector_config(){
    var parent_div_git = document.getElementsByClassName('sticky_layout')[0];
    var item_html = '<div class="card-widget card-clock"><div class="card-glass"><div class="card-background"><div class="card-content"><div id="hexo_electric_clock"><img class="entered loading" id="card-clock-loading" src= "" data-lazy-src="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/loading.gif" style="height: 120px; width: 100%;" data-ll-status="loading"/></div></div></div></div></div>';
    console.log('已挂载butterfly_clock_anzhiyu')
    parent_div_git.insertAdjacentHTML("afterbegin",item_html)
    }
  var elist = 'null'.split(',');
  var cpage = location.pathname;
  var epage = 'all';
  var qweather_key = 'f854dfdd82d747fca7fd04f092861e87';
  var gaud_map_key = '427416c518f4476a01117be40057a892';
  var baidu_ak_key = 'undefined';
  var flag = 0;
  var clock_rectangle = '112.982279,28.19409';
  var clock_default_rectangle_enable = 'false';

  for (var i=0;i<elist.length;i++){
    if (cpage.includes(elist[i])){
      flag++;
    }
  }

  if ((epage ==='all')&&(flag == 0)){
    butterfly_clock_anzhiyu_injector_config();
  }
  else if (epage === cpage){
    butterfly_clock_anzhiyu_injector_config();
  }
  </script><script src="https://widget.qweather.net/simple/static/js/he-simple-common.js?v=2.0"></script><script data-pjax src="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/clock.min.js"></script><!-- hexo injector body_end end --></body></html>